﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using monitor_2_DBwork;

namespace KeyRedactor
{
    public partial class MainForm : Form
    {

        private Guid _guid = new Guid("B9FEB26C-B2CA-4F85-B3DF-D9E977201F02");

        private const string FileName = "KeyFile.pbs";
        private const string ClientKeyFileName = "ClientLic";
        private const string ForIvanFile = "clientid";

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Update server key. Запиливает ключ из файла в картинки.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                var b = File.ReadAllBytes(FileName);
                var d = LicHelper.Decrypt(b, _guid.ToByteArray());
                var s = Encoding.UTF8.GetString(d);
                var h = LicHelper.GetHash(s);
                SetCurrentHardId(h);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
                return;
            }
            MessageBox.Show("Operation complete", "Information", MessageBoxButtons.OK);
        }

        private void SetCurrentHardId(byte[] data)
        {
            try
            {
                HardIdentifier.AddPicture("pict1", File.ReadAllBytes("Resources\\pict1"), data, 0, 5);
                HardIdentifier.AddPicture("pict2", File.ReadAllBytes("Resources\\pict2"), data, 5, 5);
                HardIdentifier.AddPicture("pict3", File.ReadAllBytes("Resources\\pict3"), data, 10, 5);
                HardIdentifier.AddPicture("pict4", File.ReadAllBytes("Resources\\pict4"), data, 15, 5);
            }
            catch (Exception)
            {
                
                throw;
            }
            
        }

        /// <summary>
        /// Create server key. Сохраняет в файл ключ для текущего компьютера.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            var str = HardIdentifier.GetCurrentHardString();
            var mas = LicHelper.Encrypt(Encoding.UTF8.GetBytes(str.ToString()), _guid.ToByteArray());
            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                File.WriteAllBytes(FileName, mas);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
                return;
            }
            MessageBox.Show("Operation Complete");
        }

        /// <summary>
        /// Создает файлы, которые будут использовать клиент и сервер.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Guid g;
                if (!Guid.TryParse(guidBox.Text, out g))
                {
                    MessageBox.Show("Invalid GUID", "Error");
                    return;
                }
                guidBox.Text = g.ToString();
                ClientsChecker.CreateLicFile(g, ClientKeyFileName);
                var forIvan = ClientsChecker.CreateForIvan(g.ToByteArray());
                if (File.Exists(ForIvanFile))
                    File.Delete(ForIvanFile);
                File.WriteAllBytes(ForIvanFile, forIvan);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var g = Guid.NewGuid();
            guidBox.Text = g.ToString();
        }

        /// <summary>
        /// DB binding key update. Привязка длл для работы с бд к файлу бд.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                var cur = GetCurrentAssemblyIdValue();
                var hash = LicHelper.GetHash(cur);
                HardIdentifier.AddPicture("pict5", File.ReadAllBytes("Resources\\pict5"), hash, 0, 5);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private static string GetCurrentAssemblyIdValue()
        {
            
            var asm = Assembly.LoadFile(Directory.GetCurrentDirectory() + '\\' + "server_db.dll");
            var obj = asm.GetCustomAttributes(typeof(GuidAttribute), true);
            if (obj.Length > 0)
            {
                var attribute = (GuidAttribute)obj[0];
                return attribute.Value;
            }
            return string.Empty;
        }
    }
}
